import cv2

# 获取内置的检测器
smile_cascade = cv2.CascadeClassifier(
    r"/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_smile.xml")
face_cascade = cv2.CascadeClassifier(
    r"/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_frontalface_alt2.xml")
# 读取图片
img = cv2.imread("face_smile.jpeg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 探测图片中的人脸
faces = face_cascade.detectMultiScale(gray)

print("found {0} face！".format(len(faces)))

for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    roi_gray = gray[y:y + h, x:x + w]
    roi_color = gray[y:y + h, x:x + w]
    smile = smile_cascade.detectMultiScale(roi_gray, scaleFactor=1.16, minNeighbors=60, minSize=(25, 25),
                                           flags=cv2.CASCADE_SCALE_IMAGE)
    print("found {0} smile！".format(len(smile)))
    for (x2, y2, w2, h2) in smile:
        cv2.rectangle(roi_color, (x2, y2), (x2 + w2, y2 + h2), (255, 0, 0), 2)
        cv2.putText(img, 'Smile', (x, y - 7), 3, 1.2, (0, 255, 0), 2, cv2.LINE_AA)

cv2.imshow('smile test', img)
cv2.imwrite("face_smile_out.jpg", img)
c = cv2.waitKey(0)
